package com.fsd.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.util.PinyinUtil;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.E_pushtemplatesService;
import com.fsd.admin.service.H_MemberService;
import com.fsd.admin.service.H_relationService;
import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.admin.dao.A_EmployeeDao;
import com.google.gson.Gson;

@Repository("h_memberServiceImpl")
public class H_MemberServiceImpl extends MainServiceImpl<A_Employee, String> implements H_MemberService{

	private String depict = "会员：";
	
    @Resource(name = "A_EmployeeDaoImpl")
	public void setBaseDao(A_EmployeeDao A_EmployeeDao) {
		super.setBaseDao(A_EmployeeDao);
	}
	
	@Resource(name = "A_EmployeeDaoImpl")
	private A_EmployeeDao objectDao;
	
	@Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParamService;
	
	//用户
    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
    
    //微信推送模板
    @Resource(name = "e_pushtemplatesServiceImpl")
	private E_pushtemplatesService pushtemplatesService;

    @Resource(name = "h_relationServiceImpl")
	private H_relationService relationService;
    


	//============================  注册管理  ============================
	/**
	 * 加载分页数据，查询所属注册会员
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListByRegister(ParametersUtil param, A_Employee employee) throws Exception{
		String sqlWhere = " A_Employee.id=H_relation.employeeid and A_Employee.deleted=0 and H_relation.companyid='" + employee.getCompanyid() + "' ";
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("code") != null && !"".equals(objectMap.get("code"))){
				sqlWhere += " and A_Employee.code like '%" + objectMap.get("code") + "%'";
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				sqlWhere += " and (A_Employee.nickname like '%" + objectMap.get("name") + 
						"%' or A_Employee.realname like '%" + objectMap.get("name") + 
						"%' or A_Employee.symbol like '%" + objectMap.get("name") + "%')";
			}
			if(objectMap.get("mobile") != null && !"".equals(objectMap.get("mobile"))){
				sqlWhere += " and A_Employee.mobile like '%" + objectMap.get("mobile") + "%'";
			}
			if(objectMap.get("status") != null && !"".equals(objectMap.get("status"))){
				sqlWhere += " and A_Employee.status = '" + objectMap.get("status") + "'";
			}
		}
		return objectDao.queryBySqlPager(param, "A_Employee, H_relation", "A_Employee.realname asc", sqlWhere);
	}
	
	

	//============================  会员管理  ============================
	/**
	 * 加载分页数据，查询删除会员
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListRecycle(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "1"));
		c.add(Restrictions.eq("type", A_EmployeeServiceImpl.rylbhy1));
		c.addOrder(Order.asc("companyname"));
		c.addOrder(Order.asc("realname"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("code") != null && !"".equals(objectMap.get("code"))){
				c.add(Restrictions.like("code", "%" + objectMap.get("code") + "%"));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.or(
						Restrictions.like("nickname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("realname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("symbol", "%" + objectMap.get("name") + "%")
						));
			}
			if(objectMap.get("mobile") != null && !"".equals(objectMap.get("mobile"))){
				c.add(Restrictions.like("mobile", "%" + objectMap.get("mobile") + "%"));
			}
			if(objectMap.get("status") != null && !"".equals(objectMap.get("status"))){
				c.add(Restrictions.eq("status", objectMap.get("status")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，查询所有会员
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListByAll(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("type", A_EmployeeServiceImpl.rylbhy1));
		c.addOrder(Order.asc("realname"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("code") != null && !"".equals(objectMap.get("code"))){
				c.add(Restrictions.like("code", "%" + objectMap.get("code") + "%"));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.or(
						Restrictions.like("nickname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("realname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("symbol", "%" + objectMap.get("name") + "%")
						));
			}
			if(objectMap.get("mobile") != null && !"".equals(objectMap.get("mobile"))){
				c.add(Restrictions.like("mobile", "%" + objectMap.get("mobile") + "%"));
			}
			if(objectMap.get("status") != null && !"".equals(objectMap.get("status"))){
				c.add(Restrictions.eq("status", objectMap.get("status")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，查询所属管理会员
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListByCompany(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("type", A_EmployeeServiceImpl.rylbhy1));
		c.addOrder(Order.asc("realname"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("code") != null && !"".equals(objectMap.get("code"))){
				c.add(Restrictions.like("code", "%" + objectMap.get("code") + "%"));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.or(
						Restrictions.like("nickname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("realname", "%" + objectMap.get("name") + "%"),
						Restrictions.like("symbol", "%" + objectMap.get("name") + "%")
						));
			}
			if(objectMap.get("mobile") != null && !"".equals(objectMap.get("mobile"))){
				c.add(Restrictions.like("mobile", "%" + objectMap.get("mobile") + "%"));
			}
			if(objectMap.get("status") != null && !"".equals(objectMap.get("status"))){
				c.add(Restrictions.eq("status", objectMap.get("status")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param branch
	 */
	public void saveObject(A_Employee employee , A_Employee a_employee) throws Exception{
		if (employee.getLoginname() != null && !employee.getLoginname().equals("")){
			String loginName = employee.getLoginname().toLowerCase();
			if (loginName.indexOf("admin") == 0){ 
				throw new BusinessException(depict + "登录名不得以“admin”字符为前缀!");
			}
		}
		Long num = 0l;
		if(employee.getId() != null && !"".equals(employee.getId())){
			//修改
			A_Employee employee_old = objectDao.get(employee.getId());
			if(employee_old == null){
				throw new BusinessException(depict + "数据不存在!");
			}
			if (employee.getLoginname() != null && !employee.getLoginname().equals("")){
				if(!employee.getLoginname().equals(employee_old.getLoginname())){
					num = objectDao.getCount("loginname = '" + employee.getLoginname() + "'");
					if (num > 0){
						throw new BusinessException(depict + "登录名已存在!");
					}
				}
			}
			if (employee.getCode() != null && !employee.getCode().equals("")){
				if(!employee.getCode().equals(employee_old.getCode())){
					num = objectDao.getCount("code = '" + employee.getCode() + "'");
					if (num > 0){
						throw new BusinessException(depict + "编码已存在!");
					}
				}
			}
			if (employee.getIdcard() != null && !employee.getIdcard().equals("")){
//				IdcardValidator.IDCardValidate2(employee.getIdcard());
				if(!employee.getIdcard().equals(employee_old.getIdcard())){
					num = objectDao.getCount("idcard = '" + employee.getIdcard() + "'");
					if (num > 0){
						throw new BusinessException(depict + "身份证号码已存在!");
					}
				}
			}
			if(!employee.getMobile().equals(employee_old.getMobile())){
				num = objectDao.getCount("mobile = '" + employee.getMobile() + "'");
				if (num > 0){
					throw new BusinessException(depict + "手机号码已存在!");
				}
			}
			boolean isRealName = false;
			if (!employee_old.getRealname().equals(employee.getRealname()))
				isRealName = true;
			if (!employee_old.getNickname().equals(employee.getNickname()))
				isRealName = true;
			if (!employee_old.getSymbol().equals(employee.getSymbol()))
				isRealName = true;
			employee_old.setCode(employee.getCode());
			employee_old.setLoginname(employee.getLoginname());
			employee_old.setRegtime(employee.getRegtime());
			employee_old.setNickname(employee.getNickname());
			employee_old.setRealname(employee.getRealname());
			employee_old.setSymbol(employee.getSymbol());
			employee_old.setIdcard(employee.getIdcard());
			employee_old.setBirthday(employee.getBirthday());
			employee_old.setBirthyear(employee.getBirthyear());
			employee_old.setBirthmonth(employee.getBirthmonth());
			employee_old.setBirthdays(employee.getBirthdays());
			employee_old.setQq(employee.getQq());
			employee_old.setEmail(employee.getEmail());
			employee_old.setMobile(employee.getMobile());
			employee_old.setMobile1(employee.getMobile1());
			employee_old.setMobile2(employee.getMobile2());
			employee_old.setTelephone(employee.getTelephone());
			employee_old.setNatives(employee.getNatives());
			employee_old.setWorkaddress(employee.getWorkaddress());
			employee_old.setHomeaddress(employee.getHomeaddress());
//			employee_old.setImagelogo(employee.getImagelogo());
//			employee_old.setImage1(employee.getImage1());
//			employee_old.setImage2(employee.getImage2());
//			employee_old.setSort(employee.getSort());
			employee_old.setAbstracts(employee.getAbstracts());
			employee_old.setSex(employee.getSex());
			employee_old.setSexname(employee.getSexname());
			employee_old.setStatus(employee.getStatus());
			employee_old.setStatusname(employee.getStatusname());
			employee_old.setRemark(employee.getRemark());
			employee_old.setUpdatedate(this.getData());//设置修改日期
			employee_old.setUpdateemployeeid(a_employee.getId());//设置修改用户id
			employee_old.setUpdateemployeename(a_employee.getRealname());//设置修改用户姓名
			objectDao.update(employee_old);
			if (isRealName){
				//修改相关模块人员信息
				this.updateAEmployeeInfo(sysParamService.getParameterMapByCore(a_employee.getCompanyid()), 
						employee_old.getClass().getSimpleName(), employee_old);
			}
		}else{
			//添加
			if (employee.getLoginname() != null && !employee.getLoginname().equals("")){
				num = objectDao.getCount("loginname = '" + employee.getLoginname() + "'");
				if (num > 0){
					throw new BusinessException(depict + "登录名已存在!");
				}
			}
			if (employee.getCode() != null && !employee.getCode().equals("")){
				num = objectDao.getCount("code = '" + employee.getCode() + "'");
				if (num > 0){
					throw new BusinessException(depict + "编码已存在!");
				}
			}
			if (employee.getIdcard() != null && !employee.getIdcard().equals("")){
//				IdcardValidator.IDCardValidate2(employee.getIdcard());
				num = objectDao.getCount("idcard = '" + employee.getIdcard() + "'");
				if (num > 0){
					throw new BusinessException(depict + "身份证号码已存在!");
				}
			}
			num = objectDao.getCount("mobile = '" + employee.getMobile() + "'");
			if (num > 0){
				throw new BusinessException(depict + "手机号码已存在!");
			}
			employee.setId(this.getUUID());//设置主键
			employee.setCompanyid(a_employee.getCompanyid());
			employee.setCompanyname(a_employee.getCompanyname());
			employee.setType(A_EmployeeServiceImpl.rylbhy1);
			employee.setTypename(A_EmployeeServiceImpl.rylbhy2);
			employee.setAdddate(this.getData());//设置添加日期
			employee.setAddemployeeid(a_employee.getId());//设置添加用户id
			employee.setAddemployeename(a_employee.getRealname());//设置添加用户姓名
			employee.setPassword(this.employeeService.getEncipherPassWord(employee.getCompanyid(), "123456"));
			employee.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(employee);
			this.relationService.saveObject(employee, a_employee);
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + employee.getId() + employee.getRealname(), a_employee, H_MemberServiceImpl.class);
	}
	
	/**
	 * 保存自行修改
	 * @param branch
	 */
	public void saveObjectSelf(A_Employee employee , A_Employee a_employee) throws Exception{
		if (employee.getLoginname() != null && !employee.getLoginname().equals("")){
			String loginName = employee.getLoginname().toLowerCase();
			if (loginName.indexOf("admin") == 0){ 
				throw new BusinessException(depict + "登录名不得以“admin”字符为前缀!");
			}
		}
		if(employee.getId() != null && !"".equals(employee.getId())){
			//修改
			A_Employee employee_old = objectDao.get(employee.getId());
			if(employee_old == null){
				throw new BusinessException(depict + "数据不存在!");
			}
			Long num = 0l;
			if (employee.getLoginname() != null && !employee.getLoginname().equals("")){
				if(!employee.getLoginname().equals(employee_old.getLoginname())){
					num = objectDao.getCount("loginname = '" + employee.getLoginname() + "'");
					if (num > 0){
						throw new BusinessException(depict + "登录名已存在!");
					}
				}
			}
			if(!employee.getMobile().equals(employee_old.getMobile())){
				num = objectDao.getCount("mobile = '" + employee.getMobile() + "'");
				if (num > 0){
					throw new BusinessException(depict + "手机号码已存在!");
				}
			}
			boolean isRealName = false;
			if (!employee_old.getRealname().equals(employee.getRealname()))
				isRealName = true;
			if (!employee_old.getNickname().equals(employee.getNickname()))
				isRealName = true;
			if (!employee_old.getSymbol().equals(employee.getSymbol()))
				isRealName = true;
			employee_old.setLoginname(employee.getLoginname());
			employee_old.setRealname(employee.getRealname());
			employee_old.setSymbol(PinyinUtil.getPinYinHeadChar(employee.getRealname()));
			employee_old.setBirthyear(employee.getBirthyear());
			employee_old.setBirthmonth(employee.getBirthmonth());
			employee_old.setBirthdays(employee.getBirthdays());
			employee_old.setMobile(employee.getMobile());
//			employee_old.setImagelogo(employee.getImagelogo());
			employee_old.setUpdatedate(this.getData());//设置修改日期
			employee_old.setUpdateemployeeid(a_employee.getId());//设置修改用户id
			employee_old.setUpdateemployeename(a_employee.getRealname());//设置修改用户姓名
			objectDao.update(employee_old);
			if (isRealName){
				//修改相关模块人员信息
				this.updateAEmployeeInfo(sysParamService.getParameterMapByCore(a_employee.getCompanyid()), 
						employee_old.getClass().getSimpleName(), employee_old);
			}
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + employee.getId() + employee.getRealname() + "自助修改信息", a_employee, A_EmployeeServiceImpl.class);
	}
	
	
	/**
	 * 充值推送消息测试
	 * @param param
	 * @throws Exception
	 */
	public void sendMessageRecharge(ParametersUtil param) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
			for (String id : idList) {
				A_Employee employee = employeeService.get(id);
				if (employee == null)
					continue;
				String wechatApiId = sysParamService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
				
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				TemplateMessage message = new TemplateMessage();
				message.setItem("first", "尊敬的：王主任", "#000000");
				message.setItem("keyword1", "2018年5月报告", "#000000");
				message.setItem("keyword2", format.format(new Date()), "#000000");
				message.setItem("remark", "详细内容请点击详情查看，如有疑问，请致电0931-4100411联系我们。", "#1111EE");
				message.setUrl("http://hjjc.gsyskc.com/wap/content-222.htm");
				pushtemplatesService.sendTemplateMessage(wechatApiId, E_pushtemplatesServiceImpl.pushHYcz, employee, message);
			}
		}
	}
	
	/**
	 * 消费推送消息测试
	 * @param param
	 * @throws Exception
	 */
	public void sendMessagePay(ParametersUtil param) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
			for (String id : idList) {
				A_Employee employee = employeeService.get(id);
				if (employee == null)
					continue;
				String wechatApiId = sysParamService.getParameterValueByCode(
						Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
				//9xEmQhyVvYkjceeUwWre60zb1ghqBrKm_u06pVbOa_M
	//			 * @param first 开头
	//			 * @param time 时间
	//			 * @param shop 门店
	//			 * @param type 消费项目
	//			 * @param amount 消费金额
	//			 * @param remark 备注
				TemplateMessage message = new TemplateMessage();
				message.setItem("first", "尊敬的："+employee.getRealname(), "#000000");
				message.setItem("keyword1", "测试1", "#000000");
				message.setItem("keyword2", "测试2", "#000000");
				message.setItem("keyword3", "测试3", "#000000");
				message.setItem("keyword4", "测试4", "#FF0000");
				message.setItem("remark", "备注信息", "#1111EE");
				pushtemplatesService.sendTemplateMessage(wechatApiId, E_pushtemplatesServiceImpl.pushHYxf, employee, message);
			}
		}
	}
	
	/**
	 * 预约推送消息测试
	 * @param param
	 * @throws Exception
	 */
	public void sendMessageReserve(ParametersUtil param) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
			for (String id : idList) {
				A_Employee employee = employeeService.get(id);
				if (employee == null)
					continue;
				String wechatApiId = sysParamService.getParameterValueByCode(
						Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
				//hOu2_EJzfZi1YJdWy30VAzhA7g1SWAogBb85kkCxDwQ
	//			 * @param first 开头
	//			 * @param type 预约项目
	//			 * @param time 时间
	//			 * @param remark 备注
				TemplateMessage message = new TemplateMessage();
				message.setItem("first", "恭喜您已经预约成功", "#000000");
				message.setItem("keyword1", "测试1", "#2BD52B");
				message.setItem("keyword2", "测试2", "#000000");
				message.setItem("remark", "备注信息", "#1111EE");
				pushtemplatesService.sendTemplateMessage(wechatApiId, E_pushtemplatesServiceImpl.pushHYyy, employee, message);
			}
		}
	}
}
